package org.simplestudio.c3p0.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**   
* @Title: PropertyUtil.java 
* @Description: 加载配置文件，加载完成后以K,V的形式缓存起来
* @author zhengzhq E-Mail:zzq0324@qq.com
* @date 2016年9月30日 上午10:15:37 
*/
public class PropertyUtil {

    /** 配置文件后缀 */
    private static final String            CONFIG_FILE_SUFFIX = ".properties";
    private static Map<String, Properties> CACHED_CONFIG      = new ConcurrentHashMap<String, Properties>();

    /**
     * 获取某个文件的配置信息
     * 
     * @param configName
     *      配置名称，等效于配置的文件名。例如：配置文件名为c3p0-default.properties，则configName为c3p0-default
     * @return
     */
    public static Properties getConfig(String configName) throws Exception {
        Properties prop = CACHED_CONFIG.get(configName);
        if (prop == null) {//该配置名称对应的配置信息未加载
            CACHED_CONFIG.put(configName, loadConfig(configName));

            prop = CACHED_CONFIG.get(configName);
        }

        return prop;
    }

    /**
     * 按需加载配置名称对应的配置信息
     * 
     * @param configName
     * @return
     */
    private synchronized static Properties loadConfig(String configName) throws Exception {
        Properties prop = CACHED_CONFIG.get(configName);
        if (prop == null) {
            InputStream is = null;
            prop = new Properties();

            try {
                is = PropertyUtil.class.getClassLoader()
                        .getResourceAsStream(configName + CONFIG_FILE_SUFFIX);
                if (is == null) {
                    throw new Exception("can't find config file by configName " + configName);
                }
                prop.load(is);
            } catch (Exception e) {
                throw e;
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {//ignore

                    }
                }
            }
        }

        return prop;
    }

}
